//
//  WmcPhotoAPI.swift
//  YPWatermarkCamera
//
//  Created by 周诗松 on 2022/3/29.
//

import Foundation
import RxSwift
import YPNetwork

struct WmcPhotoAPI {
    /// 项目列表
    /// - DocumentUrl: http://rap2.taobao.org/organization/repository/editor?id=297881&mod=498373&itf=2194164
    /// - Parameter id: 项目id
    /// - Returns: 项目model数组
    static func fetchPhotoList(id: String, pageIndex: Int, pageSize: Int, date: String? = nil) -> Observable<[WmcPhotoModel]> {
        if let date = date, !date.isEmpty {
            let path = "/api/v2/photo/list-by-date?corp_id=\(id)&date=\(date)&size=\(pageSize)&page=\(pageIndex)"
            return WmcNetworkRequest.requestData(path: path) { request in
                request.method = .get
            }.parseListModelWithClass(WmcPhotoModel.self)
        } else {
            let params: [String: Any] = ["corp_id": id, "page": pageIndex, "size": pageSize]
            return WmcNetworkRequest.requestData(path: "/api/v2/photo/list", parameters: params) { request in
                request.method = .post
            }.parseListModelWithClass(WmcPhotoModel.self)
        }
    }

    /// 项目图片同步上传接口
    /// - DocumentUrl: http://rap2.taobao.org/organization/repository/editor?id=297881&mod=498373&itf=2194165
    /// - Parameters:
    ///   - projectId: 项目id
    ///   - watermarkType: 水印类型
    ///   - watermarkInfo: 水印信息（json类型）
    ///   - imgUrl: 图片ossurl   相对路径
    ///   - date: 图片拍照时间
    /// - Returns: response
    static func upload(projectId: String? = nil, watermarkType: String? = nil, watermarkInfo: String? = nil, imgUrl: String? = nil, date: TimeInterval? = nil) -> (observable: Observable<YPNetworkResponse>, request: YPNetworkRequest) {
        var params: [String: Any] = [:]

        if let projectId = projectId {
            params["corp_id"] = projectId
        }

        if let watermarkType = watermarkType {
            params["wmc_type"] = watermarkType
        }

        if let watermarkInfo = watermarkInfo, !watermarkInfo.isEmpty {
            params["wmc_info"] = watermarkInfo
        } else {
            params["wmc_info"] = "{\"wm_id\":0}"
        }

        if let imgUrl = imgUrl {
            var url = "/"
            url.append(imgUrl)
            params["img_url"] = url
        }

        if let date = date {
            params["take_time"] = date
        }
        // 来源
        params["entry"] = YPWmcManager.shared.entry

        var requestTemp: YPNetworkRequest!
        let observable: Observable<YPNetworkResponse> = WmcNetworkRequest.requestData(path: "/api/photo/upload", parameters: params) { request in
            request.method = .post
            requestTemp = request
        }
        
        return (observable, requestTemp)
    }
    
    /// 拍照水印使用上传接口
    /// - DocumentUrl: http://rap2.taobao.org/organization/repository/editor?id=297881&mod=498373&itf=2194184
    /// - Parameters:
    ///   - watermarkType: 水印类型
    ///   - type: 1:图片 2:视频
    ///   - watermarkInfo: 水印相关信息 （备注等重复信息需要剔除）
    ///   - videoTime: 视频时长
    ///   - area: 拍照地址
    ///   - note: 备注
    ///   - success: 请求成功
    ///   - failure: 请求失败
    static func submitWatermarkInfo(watermarkType: String,
                                    type: Int,
                                    watermarkInfo: String?,
                                    videoTime: Double? = nil,
                                    area: String? = nil,
                                    note: String? = nil,
                                    activity: Int? = nil, // 积分活动
                                    entry: Int? = nil,
                                    success: ((YPNetworkResponse) -> Void)? = nil,
                                    failure: ((YPNetworkError) -> Void)? = nil) {
        var params: [String: Any] = ["wmc_type": watermarkType, "file_type": type]
        
        if let watermarkInfo = watermarkInfo, !watermarkInfo.isEmpty {
            params["wmc_info"] = watermarkInfo
        }
        
        if let videoTime = videoTime {
            params["video_time"] = "\(videoTime)"
        }
        
        if let area = area, !area.isEmpty {
            params["area"] = area
        }
        
        if let note = note, !note.isEmpty {
            params["note"] = note
        }
        
        if let activity = activity {
            params["activity"] = activity
        }
        // 来源
        if let entry = entry {
            params["entry"] = entry
        } else {
            params["entry"] = YPWmcManager.shared.entry
        }

        return WmcNetworkRequest.requestData(path: "/api/photo/take", parameters: params) { request in
            request.method = .post
        } success: { response in
            success?(response)
        } failure: { error in
            failure?(error)
        }
    }

    /// 删除照片
    /// - DocumentUrl: http://rap2.taobao.org/organization/repository/editor?id=297881&mod=498373&itf=2198787
    /// - Parameter photoId: 图片id
    /// - Returns: response
    static func deletePhoto(photoId: Int) -> Observable<YPNetworkResponse> {
        let params: [String: Any] = ["photo_id": photoId]

        return WmcNetworkRequest.requestData(path: "/api/photo/delete", parameters: params) { request in
            request.method = .post
        }
    }
    
    /// 分类首页获取图片数量
    /// - DocumentUrl: http://rap2.taobao.org/organization/repository/editor?id=297881&mod=506800&itf=2240645
    /// - Parameter projectId: 项目id
    /// - Returns: response
    static func fetchAlbumList(projectId: String) -> Observable<[WmcAlbumModel]> {
        let path = "/api/album/index?corp_id=\(projectId)"
        
        return WmcNetworkRequest.requestData(path: path) { request in
            request.method = .get
        }.parseListModelWithClass(WmcAlbumModel.self)
    }
    
    
    /// 搜索照片
    /// - DocumentUrl - http://rap2.taobao.org/organization/repository/editor?id=297881&mod=498373&itf=2265463
    /// - Parameters:
    ///   - projectId: 项目id
    ///   - watermarkId: 水印id
    ///   - pageIndex: 页码
    ///   - pageSize: 条数
    ///   - startDate: 开始日期
    ///   - endDate: 结束日期
    /// - Returns: 结果
    static func fetchWaterMarkPhoto(projectId: String, watermarkIds: [String], pageIndex: Int, pageSize: Int, startDate: String? = nil, endDate: String? = nil) -> Observable<WmcPhotoSearchResultModel> {
        
        let ids = watermarkIds.joined(separator: ",")
        var path = "/api/v2/photo/search?corp_id=\(projectId)&wm_id=\(ids)&page=\(pageIndex)&size=\(pageSize)"
        
        if let startDate = startDate, !startDate.isEmpty {
            path.append(contentsOf: "&start=\(startDate)")
        }
        
        if let endDate = endDate, !endDate.isEmpty {
            path.append(contentsOf: "&end=\(endDate)")
        }
        
        return WmcNetworkRequest.requestData(path: path) { request in
            request.method = .get
        }.parseModelWithClass(WmcPhotoSearchResultModel.self)
    }
    
    
    /// 获取拍照统计数据
    /// - DocumentUrl - http://rap2.taobao.org/organization/repository/editor?id=297881&mod=498373&itf=2240343
    /// - Parameters:
    ///   - projectId: 项目id
    ///   - startDate: 开始日期
    ///   - endDate: 结束日期
    /// - Returns: Observable<WmcPhotographStatisticsModel>
    static func fetchTakePhotoStatistics(projectId: String, startDate: String? = nil, endDate: String? = nil) -> Observable<[WmcPhotographStatisticsModel]> {
        var path = "/api/photo/date?corp_id=\(projectId)"
        
        if let startDate = startDate, !startDate.isEmpty {
            path.append(contentsOf: "&start=\(startDate)")
        }
        
        if let endDate = endDate, !endDate.isEmpty {
            path.append(contentsOf: "&end=\(endDate)")
        }

        return WmcNetworkRequest.requestData(path: path) { request in
            request.method = .get
        }.parseListModelWithClass(WmcPhotographStatisticsModel.self)
    }
}
